﻿using System;
using System.Diagnostics;
using TidyBlog.Entity;
using TidyBlog.BLL;
using System.Web;
using System.Web.Mvc;

namespace TidyBlog.MVC
{
    /// <summary>
    /// 定义每个动作前后的公共操作
    /// </summary>
    public class BaseActionFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 运行时间计时器
        /// </summary>
        protected Stopwatch PerfWatch;
        /// <summary>
        /// 当前网站设置
        /// </summary>
        protected Setup CurrentSetup;
        /// <summary>
        /// 当前用户
        /// </summary>
        protected User CurrentUser;


        public BaseActionFilter()
        {
            
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            PerfWatch = new Stopwatch();
            PerfWatch.Start();

            base.OnActionExecuting(filterContext);

            CurrentSetup = SetupBLL.Read();
            CurrentUser = InitUser();
            if (CurrentUser != null)
            {
                // 更新用户状态
                UserBLL.UpdateState(CurrentUser.UserId, filterContext.HttpContext.Request.GetClientIP());
            }

            dynamic viewBag = filterContext.Controller.ViewBag;
            viewBag.Setup = CurrentSetup;
            viewBag.User = CurrentUser;
            viewBag.Title = CurrentSetup.SiteName;
            viewBag.Keywords = CurrentSetup.Keywords;
            viewBag.Description = CurrentSetup.Description;
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            
            var viewBag = filterContext.Controller.ViewBag;
            PerfWatch.Stop();

            // 执行时间
            viewBag.ExecTime = PerfWatch.ElapsedMilliseconds;
            // 数据库访问次数
            viewBag.DbQueryCount = filterContext.HttpContext.Items.Contains("DbQueryCount") ?
                (byte)filterContext.HttpContext.Items["DbQueryCount"] : 0;
        }

        /// <summary>
        /// 读取Cookie数据初始化用户
        /// </summary>
        protected User InitUser()
        {
            User curUser = null;

            HttpCookieCollection Cookies = HttpContext.Current.Request.Cookies;
            HttpCookie userNameCookie = Cookies["UserName"], passwordCookie = Cookies["Password"];

            if (userNameCookie != null && passwordCookie != null)
            {
                string userName = userNameCookie.Value.Trim(), password = passwordCookie.Value.Trim();
                if (!String.IsNullOrEmpty(userName) && !String.IsNullOrEmpty(password))
                {
                    curUser = UserBLL.Read(userName, password);
                }
            }

            return curUser;
        }
    }
}
